package org.groovyflow.file;

import java.io.File;
import java.io.FilenameFilter;

public class Traverser {
	private FilenameFilter filter;
	private FileHandler fileHandler;
	private File root;
	
	public Traverser(File root){
		this.root = root;
	}
	public void traverse(){
		this.traverseImpl(this.root);
	}
	private void traverseImpl(File theRoot){
		File[] files = (filter == null) ? theRoot.listFiles() : theRoot.listFiles(filter);
		for(int i = 0; i < files.length; i++){
			File file = files[i];
			if(file.isDirectory())
				traverseImpl(file);
			else{
				fileHandler.handle(file);
			}
		}			
	}
	
	public void setFilter(FilenameFilter filter) {
		this.filter = filter;
	}
	
	public void setFileHandler(FileHandler fileHandler) {
		this.fileHandler = fileHandler;
	}
	
	public static void main(String[] args) throws Exception{
		
		//File f = new File("C:/eclipse3.2/dev/dynamic3/dynaGroovy/groovy");
		/*File f = new File("C:/dev/mvc-convention/groovy");
		
		Traverser trav = new Traverser(f);
		trav.setFilter(new GroovyFilter());
		X x = new X(f);
		trav.setFileHandler(x);
		trav.traverse();
		//Thread.sleep(10000);*/
		
		
        long start =  System.currentTimeMillis();
        File root = new File( "C:/dev/USBank/eductionapp/src/com/eduction") ;
        Traverser trav = new Traverser(root);
        trav.filter = new JavaFilter();

        FileMapMaker mapMaker = new FileMapMaker();
        trav.setFileHandler(mapMaker);
        trav.traverse();

        DifferenceFinder diffFinder = new DifferenceFinder();
        diffFinder.setMapFile(mapMaker.getFileMap());
        trav.setFileHandler(diffFinder);
        trav.traverse();
        long end = System.currentTimeMillis();
        System.out.println(end - start);
        //Pretty speedy.  About 250 milliseconds for a fairly large (apprx 1000 classes) codebase of .java files
		
		
		
	}	
	
	static class X implements FileHandler{
		private File root;
		X(File root){
			this.root = root;
		}
		public void handle(File f) {
			System.out.println(root);
			System.out.println(f);
			//What about abstract classes!!
			try{
				Class clazz = Class.forName("com.sample.BaseHelper", true, getClass().getClassLoader());
				System.out.println(clazz.isInterface());
				//Class.forName("com.sample.Helper");
			}catch(Exception ex){
				ex.printStackTrace();
			}
		}
	}
	
	static class JavaFilter implements FilenameFilter{
	    public boolean accept(File dir, String name) {
	        return name.endsWith(".java") || (new File(dir, name)).isDirectory();
	    }
	}	
	
}
